package com.zbl.zblproject.core.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zbl.zblproject.core.entity.AdminUser;
import com.zbl.zblproject.core.entity.RechargeLog;
import com.zbl.zblproject.core.entity.Result;
import com.zbl.zblproject.core.mapper.AdminUserMapper;
import com.zbl.zblproject.core.mapper.RechargeLogMapper;
import com.zbl.zblproject.core.service.UserService;
import com.zbl.zblproject.core.utils.ResultUtil;

import com.zbl.zblproject.core.utils.StringUtil;
import com.zbl.zblproject.member.entity.Member;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;

import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;
import java.util.UUID;

/**
 * @author youlanqiang
 * @version 1.0
 * @date 2018/11/13
 * 用户接口
 * 用户模糊查询
 */
@Controller
@RequestMapping("/user")
@Api(tags = "用户接口")
public class UserController {


    @Value("${cert-path}")
    private String certPath;

    /**
     * 充值凭证存放地址
     */
    @Value("${img-path}")
    private String imgPath;

    @Autowired
    private UserService userService;

    @Autowired
    private AdminUserMapper adminUserMapper;

    @Autowired
    private RechargeLogMapper rechargeLogMapper;

    @Autowired
    private WxMpService wxMpService;

    @Value("${wechat.local}")
    private String localUrl;

    private static Logger logger = LoggerFactory.getLogger(UserController.class);


    @GetMapping("/get-cashier")
    @ResponseBody
    @ApiOperation("获取财务")
    public Result getUserByCashier(){
        return ResultUtil.success("成功!",userService.cashier());
    }


    @PostMapping("/update")
    @ResponseBody
    @ApiOperation("更新用户")
    public Result updateUser(@RequestParam("json") String json){
        AdminUser  user = JSONObject.parseObject(json, AdminUser.class);
        if(userService.updateUser(user)){
            return ResultUtil.success("更新成功!");
        }else{
            return ResultUtil.error("更新失败!");
        }
    }

    @GetMapping("/get-leader")
    @ApiOperation("获取所有的组长")
    @ResponseBody
    public Result getLeader(){
        return ResultUtil.success("成功", userService.getLeader());
    }

    @GetMapping("/list")
    @ApiOperation("所有用户接口")
    @ResponseBody
    public Result list(){
        return ResultUtil.success("成功", userService.list());
    }

    @GetMapping("/page")
    @ApiOperation("查询用户接口")
    @ResponseBody
    public Result page(@ApiParam("分页") @RequestParam("current") Integer current,
                       @ApiParam("查询数量") @RequestParam("size") Integer size,
                       @ApiParam("查询名称") @RequestParam("search") String search){

        return ResultUtil.success("成功!", userService.page(current, size, search));
    }



    @GetMapping("/sn-list/{id}")
    @ApiOperation("根据组长来筛选")
    @ResponseBody
    public Result snList(@ApiParam("组长ID") @PathVariable Integer id){
        return ResultUtil.success("成功!", userService.snList(id));
    }

    @GetMapping("/get-auth-url")
    @ApiOperation("获取认证连接地址")
    @ResponseBody
    public String getAuthUrl(@ApiParam("回调地址") @RequestParam("url") String localUrl){
        logger.info("回调地址: {}", localUrl);

        return  wxMpService.oauth2buildAuthorizationUrl(localUrl, WxConsts.OAuth2Scope.SNSAPI_USERINFO, null);
    }




    @RequestMapping("/wx-user-info")
    @ApiOperation("用户信息")
    @ResponseBody
    public Result getUserInfo(@RequestParam("code") String code){
        try {
            WxMpOAuth2AccessToken wxMpOAuth2AccessToken = wxMpService.oauth2getAccessToken(code);
            WxMpUser user = wxMpService.oauth2getUserInfo(wxMpOAuth2AccessToken, null);
            return ResultUtil.success("验证成功!", user);
        }catch(WxErrorException e){
            e.printStackTrace();
            return ResultUtil.error("微信验证失败");
        }
    }


    @GetMapping("/get-number/{id}")
    @ResponseBody
    @ApiOperation("获取用户编号")
    public Result getUserNumber(@ApiParam("用户ID") @PathVariable int id){
        String number = adminUserMapper.selectUserNumber(id);
        return ResultUtil.success("成功!", number);
    }

    @GetMapping("/search")
    @ResponseBody
    @ApiOperation("查询用户")
    public Result searchUser(@ApiParam("名称") @RequestParam("name") String name){
        return ResultUtil.success("成功", userService.searchUser(name));
    }

    @GetMapping("/searchUserName")
    @ResponseBody
    @ApiOperation("查询用户")
    public Result searchUserName(@ApiParam("名称") @RequestParam("name") String name){
        QueryWrapper<AdminUser> userWrapper = new QueryWrapper<>();
        userWrapper.like("user_name",name).or().like("user_number",name);
        List<AdminUser> list = adminUserMapper.selectList(userWrapper);
        return ResultUtil.success("成功", list);
    }

    @GetMapping("/recharge-log/{userId}/{current}/{size}")
    @ResponseBody
    @ApiOperation("充值记录")
    public Result rechargeLog(@ApiParam("用户ID") @PathVariable int userId,
                              @ApiParam("页数") @PathVariable int current,
                              @ApiParam("数量") @PathVariable int size){
        return ResultUtil.success("成功", userService.logPage(userId, current, size));
    }

    @GetMapping("/recharge-log/{current}/{size}")
    @ResponseBody
    @ApiOperation("所有用户的充值记录")
    public Result rechargeLogOfAll(@ApiParam("页数") @PathVariable int current,
                              @ApiParam("数量") @PathVariable int size,
                                   @ApiParam("开始时间") @RequestParam String start,
                                   @ApiParam("结束时间") @RequestParam String end){
        return ResultUtil.success("成功", userService.logPage(current, size, start, end));
    }

    @GetMapping("/show-certificate/{id}")
    @ResponseBody
    @ApiOperation("显示凭证图片")
    public void showImg(@ApiParam("订单的ID") @PathVariable int id,
                        HttpServletResponse response) {
        RechargeLog log = rechargeLogMapper.selectById(id);
        if (log != null && log.getImgPath() != null) {
            File img = new File(log.getImgPath());
            if (img.exists()) {
                String ext = FilenameUtils.getExtension(log.getImgPath());
                response.setContentType("image/jpeg");
                response.addHeader("Content-Disposition",
                        "attachment;fileName=" + log.getMode() + "." + ext);// 设置文件名
                try (OutputStream stream = response.getOutputStream()) {
                    stream.write(FileUtils.readFileToByteArray(img));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @PostMapping("/recharge")
    @ResponseBody
    @ApiOperation("用户充值")
    public Result recharge(@ApiParam("用户ID") @RequestParam("userId") int userId,
                           @ApiParam("操作人ID") @RequestParam("operatorId") int operatorId,
                           @ApiParam("充值金额") @RequestParam("price") double price,
                           @ApiParam("订单备注") @RequestParam("remarks") String remarks,
                           @ApiParam("凭证图片") @RequestParam("img") MultipartFile file){
        //todo 添加订单备注和订单凭证
        try{

            if (file == null || file.isEmpty()) {
                return ResultUtil.error("没有上传任何文件!");
            }
            File imgDir = new File(imgPath);
            if (imgDir.exists()) {
                if (imgDir.isFile()) {
                    return ResultUtil.error("保存图片的路径为文件,请通知管理员!");
                }
            } else {
                if (!imgDir.mkdirs()) {
                    return ResultUtil.error("创建保存图片文件夹失败,请联系管理员!");
                }
            }
            String ext = FilenameUtils.getExtension(file.getOriginalFilename());
            if (ext == null) {
                return ResultUtil.error("只支持jpg或png格式的图片!");
            }
            if(!ext.equals("jpg") && !ext.equals("png")&&!ext.equals("JPG") && !ext.equals("PNG")){
                return ResultUtil.error("只支持jpg或png格式的图片!");
            }
            String name = UUID.randomUUID() + "." + ext;
            File targetFile = new File(imgDir, name);
            try {
                file.transferTo(targetFile);
            } catch (IOException e) {
                return ResultUtil.error("保存失败!");
            }
            if(userService.recharge(userId, operatorId, price, remarks, targetFile.toPath().toString()) != null){
                return ResultUtil.success("成功!");
            }
            return ResultUtil.error("失败");
        }catch(RuntimeException e){
            return ResultUtil.error(e.getMessage());
        }
    }

    @GetMapping("/getVipIntegral/{mobile}")
    @ApiOperation("获取展厅系统会员积分信息")
    @ResponseBody
    public Result getvipinfo(@ApiParam("用户手机号") @PathVariable String mobile) {
        Member member= adminUserMapper.getVipIntegral(mobile);
        if(member==null){
            return ResultUtil.error("no user");
        }
        return ResultUtil.success("success",member.getIntegral());
    }

    @GetMapping("/getUserById/{userId}")
    @ResponseBody
    public Result getUserById(@ApiParam("用户手机号") @PathVariable int userId) {
        AdminUser adminUser = adminUserMapper.selectById(userId);
        if(adminUser==null){
            return ResultUtil.error("no user");
        }
        return ResultUtil.success("success",adminUser);
    }
}